package admin.Controller;

import Exception.KwickKioskDBException;
import admin.BusinessLogic.BusinessLogic;
import admin.BusinessLogic.LineChart;
import admin.BusinessLogic.Validation;
import admin_gui.Admin_ChartReport;
import admin_gui.Admin_GenerateReportArea;
import admin_gui.Admin_SelectAreaReport;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

/**
 *
 * @author WEN
 */
public class AreaReportController {

    private BusinessLogic businesslogic;
    private JPanel mainPanel;
    Vector area;
    boolean[] areaItem;
    private double quantity, sales, profit;
    //private String searchField;
    private Validation validation;
    public AreaReportController(JPanel MainPanel) {
        validation = new Validation();
        try {
            //    System.out.println("in store report controller1");
            businesslogic = new BusinessLogic();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(AreaReportController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(AreaReportController.class.getName()).log(Level.SEVERE, null, ex);
        }
        mainPanel = MainPanel;
        area = new Vector();
        areaItem = new boolean[3];
        areaItem[0] = true;
  //      searchField = "";
        for (int i = 1; i < 3; i++) {
            areaItem[i] = false;
        }
    }

    public AreaReportController() {
        try {
            businesslogic = new BusinessLogic();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(AreaReportController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(AreaReportController.class.getName()).log(Level.SEVERE, null, ex);
        }
        validation = new Validation();
    }
    public void manageArea(JTable ResultTable, Vector v_head, String searchField,
            boolean[] areaItem) {
   //     System.out.println("serrchField:" + searchField);
        this.areaItem = areaItem;
       // this.searchField = searchField;
        if (areaItem[0] == true || searchField.length() == 0) {
  //          System.out.println("inmanage");
            showAreaTable(ResultTable, v_head);
        } else if (areaItem[1]) {
            showAreaTableByCity(searchField.trim(), ResultTable, v_head);
        } else if (areaItem[2]) {
            showAreaTableByProvince(searchField.trim(), ResultTable, v_head);
        } else {
            JOptionPane.showMessageDialog(null,
                    "Sorry! Can not find that information",
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void showAreaTable(JTable ResultTable, Vector v_head) {
    //    System.out.println("vector:" + area);
        area = businesslogic.getAllPostCode();
        DefaultTableModel tm = new DefaultTableModel(area, v_head);
        ResultTable.setModel(tm);
        ((DefaultTableModel) ResultTable.getModel()).fireTableStructureChanged();
    }

    private void showAreaTableByCity(String city, JTable ResultTable,
            Vector v_head) {
    //    System.out.println("vector:" + area);
        area = businesslogic.getPostCodeByCity(city);
        DefaultTableModel tm = new DefaultTableModel(area, v_head);
        ResultTable.setModel(tm);
        ((DefaultTableModel) ResultTable.getModel()).fireTableStructureChanged();
    }

    private void showAreaTableByProvince(String priv, JTable ResultTable,
            Vector v_head) {
    //    System.out.println("vector:" + area);
        area = businesslogic.getPostCodeByProvince(priv);
        DefaultTableModel tm = new DefaultTableModel(area, v_head);
        ResultTable.setModel(tm);
        ((DefaultTableModel) ResultTable.getModel()).fireTableStructureChanged();
    }

    public void showAreaReport(ArrayList rlist) {
        Admin_GenerateReportArea areaReport = new Admin_GenerateReportArea(rlist,
                mainPanel);
        areaReport.setBounds(1, 1, 762, 613);
        mainPanel.removeAll();
        mainPanel.add(areaReport);
        mainPanel.validate();
   //     System.out.println("show store");
        mainPanel.repaint();
    }

    public void showAreaReportTable(JTable ResultTable,
            ArrayList<String> reporList,
            String startDate, String endDate, Vector<String> v_head) {
        quantity = 0;
        sales = 0;
        profit = 0;
  //     System.out.println("inside tab le");
        Vector report_vec = new Vector();
        report_vec = businesslogic.getAreaReport(reporList, startDate, endDate);
        for (int j = 0; j < report_vec.size(); j++) {
            quantity = quantity + Double.parseDouble((String) ((Vector) report_vec.get(
                    j)).get(1));
            sales = sales + Double.parseDouble((String) ((Vector) report_vec.get(
                    j)).get(2));
            profit = profit + Double.parseDouble((String) ((Vector) report_vec.get(
                    j)).get(3));
        }
        DefaultTableModel tm = new DefaultTableModel(report_vec, v_head);
        ResultTable.setModel(tm);
        ((DefaultTableModel) ResultTable.getModel()).fireTableStructureChanged();
    }

    public void generateReportChart(ArrayList<String> reportList,
            String startDate, String endDate, boolean flag) {
        Vector report_vec = new Vector();
        JPanel chartPanel = new JPanel();
        report_vec = businesslogic.getAreaReport(reportList, startDate, endDate);
        String[] report_str = new String[report_vec.size()];
        for (int j = 0; j < report_vec.size(); j++) {
            report_str[j] = (String) ((Vector) report_vec.get(j)).get(0);
        }
        Admin_ChartReport chartReport = new Admin_ChartReport(mainPanel,
                reportList, 3, startDate, endDate);
        if (flag) {
            chartPanel = getLineChart(report_str, startDate, endDate);
        } else {
            chartPanel = getPieChart(report_vec);
        }
    //    System.out.println("vec" + report_vec);
        chartPanel.setBounds(1, 1, 700, 500);
        chartReport.add(chartPanel);
        chartReport.validate();
        chartReport.repaint();
        chartReport.setBounds(1, 1, 762, 613);
        mainPanel.removeAll();
        mainPanel.add(chartReport);
        mainPanel.validate();
   //     System.out.println("inside chart");
        mainPanel.repaint();
    }

    private JPanel getLineChart(String[] report_str, String startDate,
            String endDate) {
        JPanel temp = new JPanel();
        LineChart lineChart = new LineChart();
        String splitStartDate [] = new String [3];
        String splitEndDate [] = new String [3];
        int flag = validation.validReportDate(startDate, endDate);
        try {
            if(flag == 1){
                splitStartDate = startDate.split("-");
                splitEndDate = endDate.split("-");
                startDate = splitStartDate[0]+"-01-01";
                endDate = splitEndDate[0]+"-12-31";
       //         System.out.println("startDate"+startDate);
                temp = lineChart.createAreaYearPanel(report_str, startDate, endDate);
            }else if(flag == 2 ){
                splitStartDate = startDate.split("-");
                startDate = splitStartDate[0]+"-"+splitStartDate[1]+"-"+"01";
                endDate = validation.getMonthReport(endDate);
                temp = lineChart.createAreaMthPanel(report_str, startDate, endDate);
            }else if(flag == 3){
                temp = lineChart.createAreaPanel(report_str, startDate, endDate);
            }else{
                JOptionPane.showMessageDialog(null, "Sorry! Invalid date",
                    "Error", JOptionPane.ERROR_MESSAGE);
            }
        } catch (KwickKioskDBException ex) {
            JOptionPane.showMessageDialog(null, "Sorry! Can not connect to the server",
                    "Error", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(ItemReportController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return temp;
    }

    public JPanel getPieChart(Vector report_vect) {
        DefaultPieDataset data = new DefaultPieDataset();
        for (int i = 0; i != report_vect.size(); i++) {
            data.setValue((Comparable) ((Vector) report_vect.get(i)).get(0),
                    Double.parseDouble((String) ((Vector) report_vect.get(i)).get(
                    3)));
        }
        // create a chart...
        JFreeChart chart = ChartFactory.createPieChart(
                "Profit Pie Chart",
                data,
                true, // legend?
                true, // tooltips?
                false // URLs?
                );
        // create and display a frame...
        ChartPanel panel = new ChartPanel(chart);
        return panel;
    }

    public ArrayList<Double> getTotalInfo() {
        ArrayList<Double> totalInfo = new ArrayList<Double>();
        totalInfo.add(quantity);
        totalInfo.add(sales);
        totalInfo.add(profit);
        return totalInfo;
    }

    public void goBackSelectReport() {
        Admin_SelectAreaReport selectAreaPane = new Admin_SelectAreaReport(
                mainPanel);
        selectAreaPane.setBounds(1, 1, 762, 613);
        mainPanel.removeAll();
        mainPanel.add(selectAreaPane);
        mainPanel.validate();
        mainPanel.repaint();
    }

    public void goBackAreaReportPan(JPanel mainJPanel,
            ArrayList<String> reportList, String startDate, String endDate) {
        Admin_GenerateReportArea areaReport = new Admin_GenerateReportArea(
                reportList, mainJPanel, startDate, endDate);
        areaReport.setBounds(1, 1, 762, 613);
        mainJPanel.removeAll();
        mainJPanel.add(areaReport);
        mainJPanel.validate();
   //     System.out.println("show item");
        mainJPanel.repaint();
    }
}
